package com.mdxq.mall.user.service.impl;

import cn.hutool.http.server.HttpServerRequest;
import com.mdxq.mall.user.entity.AdminLoginLog;
import com.mdxq.mall.user.entity.Role;
import com.mdxq.mall.user.mapper.AdminLoginLogMapper;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.core.update.UpdateWrapper;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.mdxq.mall.user.entity.Admin;
import com.mdxq.mall.user.mapper.AdminMapper;
import com.mdxq.mall.user.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.List;

/**
 * 后台用户表 服务层实现。
 *
 * @author zdy
 * @since 2025-01-12
 */
@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin>  implements AdminService{
    //装配一个登录日志的mapper
    @Autowired
    private AdminLoginLogMapper adminLoginLogMapper;
    @Override
    public Admin login(String username, String password, HttpServletRequest request) {
        QueryWrapper queryWrapper = new QueryWrapper();
        //前边是字段，后面是客户端填写的用户名
        queryWrapper.eq("username",username);
        queryWrapper.eq("status",1);//查询状态为1（正常）的账号
        //getOne只能查到一条
        Admin admin = this.getOne(queryWrapper);
        if (admin != null){
            //第一个参数是用户填写的密码，第二个是数据库查询到加密后的密码
            if (BCrypt.checkpw(password,admin.getPassword())){
//                UpdateWrapper updateWrapper = UpdateWrapper.of(Admin.class);
                admin.setLoginTime(LocalDateTime.now());//修改登录时间
//                updateWrapper.set("LoginTime",LocalDateTime.now());
                mapper.updateByQuery(admin,true,queryWrapper);
                AdminLoginLog log = new AdminLoginLog();
                log.setAdminId(admin.getId());
                log.setIp(request.getRemoteHost());
                log.setAddress(request.getRemoteAddr());
                log.setCreateTime(LocalDateTime.now());
                log.setUserAgent(request.getHeader("user-agent"));
                adminLoginLogMapper.insert(log);
                return admin;
            }
        }
        return null;
    }

    @Override
    public List<Role> getRoleList(Long id) {
        return mapper.selectRolesByAdminId(id);
    }

    //重写getById方法，注入角色和菜单数据
    @Override
    public Admin getById(Serializable id) {
        Admin admin = super.getById(id);//先调用父类的getById
        admin.setRoles(mapper.selectRolesByAdminId(admin.getId()));//注入管理员
        admin.setMenus(mapper.selectMenusByAdminId(admin.getId()));//注入菜单
        return admin;
    }
}
